package com.dcy.znoa.service.estate.impl;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.znoa.common.enums.EstateServiceType;
import com.dcy.znoa.common.enums.OperTypeCode;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.DateUtil;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.estate.model.service.SelectEstateServiceModel;
import com.dcy.znoa.controller.estate.model.service.UpdateEstateServiceModel;
import com.dcy.znoa.controller.publiz.model.messNotice.AddMessNoticeListAndMsgModel;
import com.dcy.znoa.controller.sys.model.storeFile.AddStoreFileModel;
import com.dcy.znoa.dao.estate.EstateServiceMapper;
import com.dcy.znoa.dao.publiz.CompanyDao;
import com.dcy.znoa.dao.user.OperDao;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.estate.EstateAdvice;
import com.dcy.znoa.domain.estate.EstateService;
import com.dcy.znoa.domain.publiz.Company;
import com.dcy.znoa.service.estate.EstateServiceService;
import com.dcy.znoa.service.publiz.MessNoticeService;
import com.dcy.znoa.service.sys.StoreFileService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import static com.dcy.znoa.common.enums.EstateServiceType.REPAIR;

/**
 * <p>
 * 物业服务表 服务实现类
 * </p>
 *
 * @author cook
 * @since 2018-05-21
 */
@Service
public class EstateServiceServiceImpl implements EstateServiceService {

    @Autowired
    EstateServiceMapper esMapper;
    @Autowired
    CompanyDao companyDao;
    @Autowired
    OperDao operDao;
    @Autowired
    StoreFileService storeFileService;
    @Autowired
    MessNoticeService messNoticeService;


    @Override
    public JsonForList selectList(SelectEstateServiceModel model) throws InvocationTargetException, IllegalAccessException {
        EntityWrapper<EstateService> ew = new EntityWrapper<>();
        EstateService cp = new EstateService();
        BeanUtils.copyProperties(cp, model);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<EstateService> list = esMapper.selectListMapper(model, page);
        return new JsonForList(list, page.getTotal());
    }
    @Transactional
    @Override
    public Integer insert(EstateService cp) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        //1 新增
        //查询出对应的esId receiveOperId
        Long compId = cp.getCompId();
        if (compId == null) {
            throw new BusinessException("404", "登录用户没有归属的企业");
        }
        Company company = companyDao.selectById(compId);
        if (company == null) {
            throw new BusinessException("404", "登录用户没有归属的企业");
        }
        Long esId = company.getEsId();
        if (esId == null) {
            throw new BusinessException("404", "登录用户对应企业没有绑定的物业公司");
        }
        cp.setEsId(esId);
        cp.setStatus(1);//1 待接单
        Oper queryOper = new Oper();
        queryOper.setCompId(esId);
        queryOper.setOperType(OperTypeCode.PLACEMGR.getCode());//物业管理员
        List<Oper> operList = operDao.selectOperList(queryOper);
        if (operList == null || operList.isEmpty()) {
            throw new BusinessException("404", "登录用户对应企业对应的物业公司没有管理员");
        }
        Long receiveOperId = operList.get(0).getOperId();
        cp.setReceiveOperId(receiveOperId);
        Integer result1 = esMapper.insert(cp);
        if (result1 ==null || result1 <= 0) {
            throw new BusinessException("404", "新增物业服务单失败");
        }
//        //2 不需要  操作附件表 因为 下面的 insertBatchAndMsg会做这个事情
//        if(StringUtils.isNotBlank(cp.getRemoteFileName())){
//            AddStoreFileModel addStoreFileModel = new AddStoreFileModel();
//            BeanUtils.copyProperties(addStoreFileModel, cp);
//            addStoreFileModel.setEntityTbl("estate_service");
//            addStoreFileModel.setEntityId(cp.getEsserId());
//            Integer result2 = storeFileService.addBatch(addStoreFileModel);
//            if (result2 == null || result2 <= 0) {
//                throw new BusinessException("404", "新增物业服务单附件失败");
//            }
//        }
        //3 发APP内部消息
        AddMessNoticeListAndMsgModel amnlModel = new AddMessNoticeListAndMsgModel();
        BeanUtils.copyProperties(amnlModel, cp);
        EstateServiceType estateServiceType = EstateServiceType.getMsgByCode(cp.getType());
        amnlModel.setMessage(estateServiceType.getMsg()+":预约时间为："+ DateUtil.getFormatDate(cp.getBespeakTime())+";地点："+cp.getAddress() );
        amnlModel.setMessTitle(estateServiceType.getMsg()+"服务单");
        amnlModel.setCreateOperId(cp.getCreateOperId());
        amnlModel.setOperIdsStr(String.valueOf(receiveOperId));
        amnlModel.setEntityId(cp.getEsserId());
        amnlModel.setEntityTbl("estate_service");
        amnlModel.setMessType(9);//9表示物业
        //给接收人的消息
        Long messId = messNoticeService.insertBatchAndMsg(amnlModel);
        if(messId==null||messId<0){
            throw new BusinessException("404", "新增物业服务单-内部消息发送失败");
        }
        return 1;
    }
    @Transactional
    @Override
    public Integer updateById(UpdateEstateServiceModel model) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        if (model == null || model.getEsserId() == null) {
            throw new BusinessException("404", "入参esserId不能为空");
        }
        EstateService cp = new EstateService();
        BeanUtils.copyProperties(cp, model);
        cp.setUpdateTime(new Date());
        Integer status = model.getStatus();
        if (status != null) {
            switch (status) {
                case 1:// 1 待接单：目前不需要做操作
                    break;
                case 2:// 2 已接单
                    cp.setReceiveReceiveTime(new Date());
                    break;
                case 3://3 处理中:就是服务人员收到消息后，APP调用这个接口，这个状态就变成处理中
                    Long handleOperId = model.getHandleOperId();
                    if(handleOperId==null){
                        throw new BusinessException("404", "入参status为已接单时，handleOperId不能为空");
                    }
                    cp.setReceiveReceiveTime(new Date());
                    AddMessNoticeListAndMsgModel amnlModel = new AddMessNoticeListAndMsgModel();
                    amnlModel.setMessage("一个分配的服务单任务");
                    amnlModel.setMessTitle("服务单子任务");
                    amnlModel.setCreateOperId(cp.getReceiveOperId());
                    amnlModel.setOperIdsStr(String.valueOf(handleOperId));
                    amnlModel.setEntityId(cp.getEsserId());
                    amnlModel.setEntityTbl("estate_service");
                    amnlModel.setMessType(9);//9表示物业
                    //给接收人的消息
                    Long messId = messNoticeService.insertBatchAndMsg(amnlModel);
                    if(messId==null||messId<0){
                        throw new BusinessException("404", "更新物业服务单-内部消息发送失败");
                    }
                    cp.setHandleReceiveTime(new Date());
                    break;
                case 4:// 处理完成
                    cp.setEndTime(new Date());
                    break;
                default:
                    throw new BusinessException("404", "入参status有误，不能为："+status);
            }
        }
        return esMapper.updateById(cp);
    }

    @Override
    public EstateService selectById(Long esserId) {
        SelectEstateServiceModel model = new SelectEstateServiceModel();
        model.setEsserId(esserId);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<EstateService> list =  esMapper.selectListMapper(model,page);
        if(list!=null && list.size()>0){
            return list.get(0);
        }
        return null;
    }
}
